package com.wuster.controller;

import com.wuster.entity.Product;
import com.wuster.entity.dto.ProductDTO;
import com.wuster.result.PageResult;
import com.wuster.result.Result;
import com.wuster.result.ResultCodeEnum;
import com.wuster.service.ProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@Slf4j
@RestController
@RequestMapping("/product")
@Api(tags="商品相关接口")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/getProductDetails/{pid}")
    @ApiOperation("根据id获取商品详情")
    public Result getProductDetails(@PathVariable("pid") Long pid){
        log.info("获取商品{}详情", pid);
        Result result = productService.getDetailById(pid);
        return result;
    }

    @PostMapping("/setProductStatus")
    @ApiOperation("设置商品上下架状态")
    public Result setStatus(@RequestBody ProductDTO productDTO){
        Result result = productService.setStatus(productDTO);
        return result;
    }

    @DeleteMapping("/deleteProduct/{productId}")
    @ApiOperation("删除商品")
    public Result deletePrduct(@PathVariable("productId") Long pid){
        log.info("删除商品{}", pid);
        Result result = productService.delProduct(pid);
        return result;
    }


    @PostMapping("/modifyProduct")
    @ApiOperation("修改商品信息")
    public Result modifyProduct(@RequestBody ProductDTO productDTO){
        Long id = productDTO.getProductId();
        log.info("修改商品{}信息", id);
        Result result = productService.updateProduct(productDTO);

        return result;
    }

    @PostMapping("/addProduct")
    @ApiOperation("添加商品")
    public Result addProduct(@RequestBody ProductDTO productDTO){
        log.info("添加商品{}", productDTO.getName());
        Result res = productService.addProduct(productDTO);
        return res;
    }


    @GetMapping("/getProductList/{pageId}")
    @ApiOperation("商品分页查询")
    public Result getProductList(@PathVariable Integer pageId, @RequestParam(required=false, value="qName") String name,
                                 @RequestParam(required=false, value="categoryId") Long categoryId){
        // 判断页码是否正确
        if (pageId <= 0)
            return Result.error(ResultCodeEnum.PAGE_ID_INVALID.getCode(), ResultCodeEnum.PAGE_ID_INVALID.getMessage());
        PageResult list = productService.getList(pageId, name, categoryId);
        return Result.success(list);
    }
}
